import { Component, toNative } from 'vue-facing-decorator'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import type { FilterDto } from '@/render/FilterRender'
import type { VxeColumnSlotTypes, VxeGridPropTypes, VxeTableDataRow } from 'vxe-table'
import type { AnyObject } from '@/types'
import {
    AllowStatusCnEnum,
    getKeyToEnum,
    InvoiceFromCnEnum,
    InvoiceTypeCnEnum,
    InvoiceUploadStatusCnEnum
} from '@/const/enum'
import DialogUpload from './components/DialogUpload'
import {
    exportInvoice,
    getInvoiceBatchList,
    getNeedSyncInvoiceList,
    uploadBatchInvoiceZip,
} from '@/api/invoice'
import type { BatchInvoiceDto, InvoiceDto } from '@/api/invoice/types'
import { downloadFile } from '@/utils/util'
import { getModelValue, initModelValue, renderForm, type FormModalDto } from '@/components/modal/Modal'
import DialogHandleConflictInvoice from './components/DialogHandleConflictInvoice'
import PreviewImageOrPdf from '@/components/preview-media/PreviewImageOrPdf'
import dayjs from 'dayjs'
import { Button, message, type UploadFile } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'
@Component
export class BatchUpload extends TableRender {
    showUploadZip = false
    showUpload = false

    showInvoice = false

    uploadFile = null as File | null
    curItem = {} as InvoiceDto

    invoiceSyncList = [] as (InvoiceDto | BatchInvoiceDto)[]

    showDate = true

    filterConfig() {
        return {
            companyName: {
                name: '企业名称',
                element: 'input'
            },
            type: {
                name: '发票类型',
                element: 'select',
                options: getKeyToEnum(InvoiceTypeCnEnum, true)
            },
            isSync: {
                name: '是否同步',
                element: 'select',
                options: getKeyToEnum(AllowStatusCnEnum, true)
            },
            month: {
                name: '应用月份',
                element: 'datetime',
                params: {
                    type: 'month',
                    valueFormat: 'YYYY-MM'
                }
            }
        } as FilterDto
    }

    tableColumnConfigOld = () => [
        {
            field: 'companyName',
            title: '企业名称',
            width: 200
        },
        {
            field: 'invoiceNo',
            title: '发票标识号',
            width: 180
        },
        {
            field: 'invoiceName',
            title: '发票名称',
            width: 200
        },
        {
            field: 'updateTime',
            title: '上传时间',
            width: 160,
            formatter: ({ row }) => {
                return row.updateTime ? dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss') : '--'
            }
        },
        {
            field: 'isSync',
            title: '是否同步',
            formatter: ({ row }) => {
                return AllowStatusCnEnum[row.isSync]
            }
        },
        {
            field: 'type',
            title: '发票类型',
            formatter: ({ row }) => {
                return InvoiceTypeCnEnum[row.type]
            }
        },
        {
            field: 'openAmount',
            title: '原始发票金额',
            width: 120,
            slots: {
                default: 'price'
            }
        },
        {
            field: 'invoiceMonth',
            title: '应用月份'
        },
        {
            field: 'syncAmount',
            title: '应用月份金额',
            width: 120,
            slots: {
                default: 'price'
            }
        },
        {
            field: 'invoiceUrl',
            title: '预览',
            slots: {
                default: ({ row, column }: VxeColumnSlotTypes.ContentSlotParams) => {
                    return (
                        <>
                            <PreviewImageOrPdf src={row.invoiceUrl} />
                        </>
                    )
                }
            }
        },
        {
            field: 'createTime',
            title: '创建时间',
            width: 160,
            formatter: ({ row }) => {
                return row.updateTime ? dayjs(row.updateTime).format('YYYY-MM-DD HH:mm:ss') : '--'
            }
        },
        {
            field: 'operate',
            title: '操作',
            fixed: 'right',
            width: 60,
            params: {
                buttons: [
                    {
                        text: '处理',
                        event: (row: InvoiceDto) => {
                            this.onHandleInvoice(row)
                        }
                    }
                ]
            },
            slots: {
                default: 'buttons'
            }
        }
    ] as TableRenderColumnTypes<BatchInvoiceDto>

    basicFormConfig = this.initBasicFormConfig() as FormModalDto
    initBasicFormConfig() {
        return {
            title: '',
            width: '400px',
            theme: 'light',
            show: false,
            items: {
                invoiceFrom: {
                    name: '付款方式',
                    element: 'select',
                    defaultValue: 1,
                    required: true,
                    params: {
                        clearable: false,
                    },
                    options: getKeyToEnum(InvoiceFromCnEnum)
                }
            },
            complete: async () => {},
            cancel: () => {
                this.basicFormConfig.show = false
            },
            init: () => {
                initModelValue(this.basicFormConfig)
            }
        } as FormModalDto
    }

    basicForm = {
        validate: async () => {},
        clear: () => {},
        element: () => <> </>
    }

    onUploadZip() {
        this.showUploadZip = true
    }

    async onShowHandleInvoice() {
        this.invoiceSyncList = await this.getInvoiceList()
        this.showDate = true
        this.showInvoice = true
    }

    onHandleInvoice(row: InvoiceDto) {
        this.invoiceSyncList = [row]
        this.showDate = false
        this.showInvoice = true
    }

    async onExport() {
        const params = this.getFilters()
        params.status = InvoiceUploadStatusCnEnum.已上传
        const res = await exportInvoice(params)
        downloadFile(res)
    }

    async onConfirm(data: { file: UploadFile[]; close: () => void }, type: string) {
        if (!data.file?.length) {
            message.warning('请先上传文件')
            return
        }
        const fileData = new FormData()
        fileData.append('file', data.file[0]?.originFileObj as File)

        const params = getModelValue(this.basicFormConfig)

        fileData.append('invoiceFrom', params.invoiceFrom)

        await uploadBatchInvoiceZip(fileData)

        message.success('上传成功')
        this.reloadPage()
        data.close()
    }

    async getInvoiceList() {
        const res = await getNeedSyncInvoiceList({
            isSync: 0,
            month: ''
        })
        return res
    }

    onLoadData(page: number, size: number, filters: AnyObject) {
        console.log(121111)
        return getInvoiceBatchList({
            pageNum: page,
            pageSize: size,
            ...filters
        })
    }

    async onMounted() {
        this.basicForm = renderForm(this.basicFormConfig)
    }

    renderRightBtns() {
        return (
            <div class="flex gap-20px">
                <Button icon={h(UploadOutlined)} onClick={this.onUploadZip}>
                    上传
                </Button>
                <Button icon={h(UploadOutlined)} onClick={this.onShowHandleInvoice}>
                    批量处理
                </Button>
            </div>
        )
    }

    render() {
        return (
            <>
                {super.render()}
                <DialogUpload
                    v-model:show={this.showUploadZip}
                    onConfirm={(event) => this.onConfirm(event, 'zip')}
                    accept=".zip"
                    v-slots={{
                        header: () => {
                            return <div>
                                <div class="text-lg font-bold mb-20px">上传发票</div>
                                <>{this.basicForm.element()}</>
                            </div>
                        },
                        default: () => {
                            return (
                                <div class="text-red">
                                    <div>
                                        批量上传电子签发票文件名格式：电子签__年-月.zip；如：电子签__2022-01.zip
                                    </div>
                                    <div>
                                        批量上传日日保发票文件名格式：日日保__年-月.zip；如：日日保__2022-01.zip
                                    </div>
                                </div>
                            )
                        }
                    }}
                />

                <DialogUpload
                    v-model:show={this.showUpload}
                    onConfirm={(event) => this.onConfirm(event, 'single')}
                />
                <DialogHandleConflictInvoice v-model:show={this.showInvoice} showDate={this.showDate} invoicelist={this.invoiceSyncList} onConfirm={this.reloadPage}/>
            </>
        )
    }
}

export default toNative(BatchUpload)
